package com.jieshuibao.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.config.enumtype.ResponseCode;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.mapper.RegistResponse;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.Card;
import com.jieshuibao.model.db.Category;
import com.jieshuibao.model.db.CmsCategory;
import com.jieshuibao.model.db.Company;
import com.jieshuibao.model.db.Counselor;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.Level;
import com.jieshuibao.model.db.QuestionEx;
import com.jieshuibao.model.db.QuestionExample;
import com.jieshuibao.model.db.QuestionExample.Criteria;
import com.jieshuibao.model.db.QuestionUserEx;
import com.jieshuibao.model.db.RedEnvelopes;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.AddAdmireResponse;
import com.jieshuibao.model.domain.Article;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.FindPwdOneRequest;
import com.jieshuibao.model.domain.FindPwdOneResponse;
import com.jieshuibao.model.domain.Integrals;
import com.jieshuibao.model.domain.LoginRequest;
import com.jieshuibao.model.domain.LoginResponse;
import com.jieshuibao.model.domain.PageRequest;
import com.jieshuibao.model.domain.SearchResponse;
import com.jieshuibao.model.domain.UpdatePwdRequest;
import com.jieshuibao.model.domain.UserLevel;
import com.jieshuibao.service.AnswerUserService;
import com.jieshuibao.service.ArticelService;
import com.jieshuibao.service.CardBatchService;
import com.jieshuibao.service.CardService;
import com.jieshuibao.service.CategoryService;
import com.jieshuibao.service.ChangeCodeService;
import com.jieshuibao.service.CmsArticleService;
import com.jieshuibao.service.CompanyService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.CounselorService;
import com.jieshuibao.service.IntegralService;
import com.jieshuibao.service.LevelService;
import com.jieshuibao.service.MessageService;
import com.jieshuibao.service.QuestionExService;
import com.jieshuibao.service.QuestionService;
import com.jieshuibao.service.QuestionUserService;
import com.jieshuibao.service.RedEnvelopesService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.SmsSendService;
import com.jieshuibao.service.UserDealRecordService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.util.CookieGenerator;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
public class IndexController {
	private static final Logger logger = LoggerFactory
			.getLogger("IndexController.class");

	private static final ObjectMapper mapper = new ObjectMapper();
	@Resource
	private UserService userService;
	@Resource
	private RedisService redisService;
	@Resource
	private CounselorService counselorService;
	@Resource
	private LevelService levelService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private CounselorDutyService counselorDutyService;
	@Resource
	private AnswerUserService answerUserService;
	@Resource
	private QuestionService questionService;
	@Resource
	private QuestionUserService questionUserService;
	@Resource
	private QuestionExService questionExService;
	@Resource
	private CompanyService companyService;
	@Resource
	private SmsSendService smsSendService;
	@Resource
	private ChangeCodeService changeCodeService;
	@Resource
	private IntegralService IntegralService;
	@Resource
	private RedEnvelopesService redEnvelopesService;
	@Resource
	private CardService cardService;
	@Resource
	private UserDealRecordService userDealRecordService;
	@Resource
	CardBatchService cardBatchService;
	@Resource
	private ArticelService articelService;
	@Resource
	private CmsArticleService cmsArticleService;
	@Resource
	private MessageService messageService;
	
	@Value("${head.images.url}")
	private String headImagesUrl;

	// 登录
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Object login(HttpServletRequest request,
			@RequestBody LoginRequest loginRequest) {
		LoginResponse loginResponse = new LoginResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(loginRequest));
			String phoneNumber = loginRequest.getPhoneNumber();
			String pwd = loginRequest.getPwd();
			String smsMessageSid = loginRequest.getSmsMessageSid();
			String code = loginRequest.getCode();//图片验证码
			String regExp = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
			Pattern p = Pattern.compile(regExp);
			if (phoneNumber != null && !phoneNumber.equals("") && 
					(pwd != null || !StringUtils.isBlank(smsMessageSid))) {
				Matcher m = p.matcher(phoneNumber);
				if (m.matches()) {
					User loginUser =userService.getUserByphone(phoneNumber);
					if(null != loginUser){
						Integer role = loginUser.getRole();
						String phoneNumber2 = loginUser.getPhoneNumber();
						if (role == 0) {
							// 你的账号已被冻结
							loginResponse.setCode("5");
							loginResponse.setDes("账号异常，请联系管理员");
							return loginResponse;
						} else if(role == 3){
							loginResponse.setCode("6");
							loginResponse.setDes("进行下一步");
							return loginResponse;
						}else {
							boolean smsLoginPassed = false;
							boolean smsCodePassed = false;
							if(StringUtils.isBlank(pwd)){//无密码-短信登录
								smsLoginPassed = true;
								Map<String, String> checkSms = changeCodeService.checkSmsApp(smsMessageSid, code,phoneNumber);
								String codeValue = checkSms.get("code");
								if(codeValue.equals("1")){
									smsCodePassed = true;
								}
							}
							//如果不是短信登录，校验用户是否存在密码，不存在密码则只能使用短信验证码登录
							if (!smsLoginPassed && StringUtils.isBlank(loginUser.getPwd())) {
								loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
								loginResponse.setDes("用户无密码，请使用短信登录");
								return loginResponse;
							}
							if(smsLoginPassed && !smsCodePassed){
								loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
								loginResponse.setDes("短信验证码错误");
								return loginResponse;
							}
							
							if (smsLoginPassed || loginUser.getPwd().equals(pwd)) {

								String cookie = CookieGenerator.generateCookie(phoneNumber2);
								Set<String> keys = redisService.keys("C_"+ phoneNumber2 + "*");
								CookieUser cookieUser = new CookieUser();
								cookieUser.setPhone(phoneNumber);
								cookieUser.setPhoneNumber(phoneNumber2);
								int deviceType = loginRequest.getDeviceType();
								cookieUser.setDeviceType(deviceType);
								if (keys.size() == 0) {
									redisService.setObject(cookie, cookieUser,0);
								} else {
									for (String key : keys) {
										redisService.delete(key);
									}
									redisService.setObject(cookie, cookieUser,0);
											
								}
								if (loginUser.getSex() == null) {
									loginResponse.setGender("男");
								} else if (loginUser.getSex() == 2) {
									loginResponse.setGender("女");
								} else {
									loginResponse.setGender("男");
								}
								loginResponse.setCode("1");
								loginResponse.setCookieId(cookie);
								if (loginUser.getBirthdayDate() != null) {
									SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
									String format = dateFormater.format(loginUser.getBirthdayDate());
									
									loginResponse.setBirthday(format);
											
								}
								String counselorDuty = loginUser.getCounselorDuty();
										
								StringBuilder stringBuilder = new StringBuilder();
								if (counselorDuty != null
										&& !counselorDuty.equals("")) {
									String[] split = counselorDuty.split(",");

									for (String id : split) {
										if (id != null && !id.equals("")) {
											Duty duty = counselorDutyService
													.getDutyById(id);
											if (duty != null) {

												stringBuilder.append(duty
														.getDutyName() + " ");
											}
										}

									}
									loginUser.setCounselorDuty(stringBuilder
											.toString());

								}
								BeanUtils.copyProperties(loginResponse,
										loginUser);

								if (loginUser.getCounselorUuid() != null) {
									Counselor counselor = counselorService
											.getCounselorByUuid(loginUser
													.getCounselorUuid());
									if (counselor != null) {
										Date applyDate = counselor.getApplyDate();
												
										if (applyDate != null) {
											loginResponse.setApplyTime(applyDate);
													
										}
										String counselorLevel = counselor.getCounselorLevel();
												

										if (counselorLevel != null
												&& !counselorLevel.equals("")) {
											Level level = levelService.getLevelByUuid(counselor.getCounselorLevel());
															
											loginResponse.setLevelName(level.getName());
													
											loginResponse.setLevelMoney(level.getMoney());
													
										}

										String adept = counselor.getAdept();
										if (adept != null && !adept.equals("")) {
											String[] adeps = adept.split(",");
											HashMap<String, String> map = new HashMap<String, String>();
											for (String categoyrUuid : adeps) {
												if (categoyrUuid != null) {
													Category categoryById = categoryService.getCategoryById(categoyrUuid);
															
													if (categoryById != null) {
														map.put(categoyrUuid,categoryById.getName());
																
																		
													}

												}

											}
											loginResponse.setAdepts(map);
										}
										BeanUtils.copyProperties(loginResponse,
												counselor);
									}

								}
								String companyUuid = loginUser.getCompanyUuid();
								Company company = companyService.getCompanyByUuid(companyUuid);
								if(company!=null){
									loginResponse.setCompanyLog(company.getCompanyLog());
									loginResponse.setBusinessBalance(company.getBusinessBalance());
									loginResponse.setCompanyStataus(company.getStatus());
								}
								Integrals integrals = IntegralService.getIntegralsByUuid(phoneNumber);
								if (integrals==null) {
									loginResponse.setIntegralScore(0);
								}else {
									int integralSum = integrals.getIntegralSum();
									loginResponse.setIntegralScore(integralSum);
								}
								loginResponse.setCode(BaseRes.SUCCESS_CODE);
								loginResponse.setDes("登录成功");
								loginResponse.setHeadImageUrl(headImagesUrl);
								loginResponse.setCookieId(cookie);
								List<Answer> answerByPhone = answerUserService.getAnswerByPhone(phoneNumber);
										
								if (answerByPhone != null
										&& answerByPhone.size() > 0) {
									Answer answer = answerByPhone.get(0);
									String questionUuid = answer
											.getQuestionUuid();
									QuestionUserEx questionExByUuid = questionExService.getQuestionExByUuid(questionUuid);
									String counselor = questionExByUuid.getCounselorDuty();
									if(counselor!=null&&!counselor.equals("")){
										StringBuilder stringBuilder1=new StringBuilder();
										String[] dutys = counselor.split(",");
										if(dutys!=null){
											for (String id : dutys) {
												if(id!=null&&!id.equals("")){
													Duty duty = counselorDutyService.getDutyById(id);
													if(duty!=null){
														stringBuilder1.append(duty.getDutyName()+" ");
													}
													
												}
												
											}
											questionExByUuid.setCounselorDuty(stringBuilder1.toString());
										}
										
									}
									loginResponse.setDes("您有未回答的问题，请前去回答");
									loginResponse.setQuestion(questionExByUuid);
									loginResponse.setCode("4");
								}

							} else {
								loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
								loginResponse.setDes("用户名密码不匹配!");
								return loginResponse;
							}
						}
					}else {
						loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
						loginResponse.setDes("用户不存在，请注册后登录!");
						return loginResponse;
					}
					//当前用户是否存在密码
					if(StringUtils.isBlank(loginUser.getPwd())){
						loginResponse.setIfPwd(0);
					}else{
						loginResponse.setIfPwd(1);
					}
				} else {
					loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
					loginResponse.setDes("请输入正确手机号！");
				}

			}else {
				loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
				loginResponse.setDes("用户名密码不能为空");
			}
			/*
			 * }else { //数据格式错误呀 loginResponse.setCode("3");
			 * loginResponse.setDes("亲 数据格式错误了呀"); }
			 */

			/*
			 * }else { //数据格式错误呀 //数据格式错误呀 loginResponse.setCode("3");
			 * loginResponse.setDes("亲 数据格式错误了呀"); }
			 */

			logger.info("返回：" + mapper.writeValueAsString(loginResponse));
		} catch (Exception e) {
			e.printStackTrace();
			loginResponse.setCode("0");
			loginResponse.setDes("系统繁忙请稍后再试！");
		}
		return loginResponse;
	}
	
	// role=3 的用户首次登陆（从盒子带来的用户）
	@RequestMapping(value = "/utvlogin", method = RequestMethod.POST)
	@ResponseBody
	public Object uTvLogin(HttpServletRequest request,
			@RequestBody LoginRequest loginRequest) {
		LoginResponse loginResponse = new LoginResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(loginRequest));
			String phoneNumber = loginRequest.getPhoneNumber();
			String pwd = loginRequest.getPwd();
			String code = loginRequest.getCode();
			String smsMessageSid = loginRequest.getSmsMessageSid();
			String regExp = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
			Pattern p = Pattern.compile(regExp);
			if (phoneNumber != null && !phoneNumber.equals("") && pwd != null) {
				Matcher m = p.matcher(phoneNumber);
				if (m.matches()) {
					User loginUser =userService.getUserByphone(phoneNumber);
					if(null != loginUser){
						Integer role = loginUser.getRole();
						String phoneNumber2 = loginUser.getPhoneNumber();
						if (role !=3) {
							
							loginResponse.setCode("5");
							loginResponse.setDes("账号异常，请联系管理员");
							return loginResponse;
						} else {
								if (loginUser.getPwd().equals(pwd)) {
									String cookie = CookieGenerator.generateCookie(phoneNumber2);
									Set<String> keys = redisService.keys("C_"+ phoneNumber2 + "*");
									CookieUser cookieUser = new CookieUser();
									cookieUser.setPhone(phoneNumber);
									cookieUser.setPhoneNumber(phoneNumber2);
									int deviceType = loginRequest.getDeviceType();
									cookieUser.setDeviceType(deviceType);
									if (keys.size() == 0) {
										redisService.setObject(cookie, cookieUser,0);
									} else {
										for (String key : keys) {
											redisService.delete(key);
										}
										redisService.setObject(cookie, cookieUser,0);
												
									}
									if(code==null||code.equals("")){
										loginResponse.setCode(BaseRes.ERRORPARAM_CODE);//
										loginResponse.setDes("验证码不能为空");
										return loginResponse;
									}
									if(StringUtils.isEmpty(smsMessageSid)){
										loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
										loginResponse.setDes("数据错误！");
										return loginResponse;
									}
									Map<String, String> checkSms = changeCodeService.checkSmsApp(smsMessageSid, code,phoneNumber);
									String codeValue = checkSms.get("code");
									if(!codeValue.equals("1")){
										return checkSms;
									}
									User user = new User();
									String uuid = loginUser.getPhoneNumber();
									user.setPhoneNumber(uuid);
									user.setRole(Const.USER_ROLE_1);
									userService.updateUser(user);
									BeanUtils.copyProperties(loginResponse,
											loginUser);
									if (loginUser.getSex() == null) {
										loginResponse.setGender("男");
									} else if (loginUser.getSex() == 2) {
										loginResponse.setGender("女");
									} else {
										loginResponse.setGender("男");
									}
									Integrals integrals = IntegralService.getIntegralsByUuid(phoneNumber);
									if (integrals==null) {
										loginResponse.setIntegralScore(0);
									}else {
										int integralSum = integrals.getIntegralSum();
										loginResponse.setIntegralScore(integralSum);
									}
									loginResponse.setRole(Const.USER_ROLE_1);
									loginResponse.setCode(BaseRes.SUCCESS_CODE);
									loginResponse.setCookieId(cookie);
									loginResponse.setDes("登录成功");
								} else {
									loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
									loginResponse.setDes("用户名密码不匹配");
								}
						}
					}else {
						loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
						loginResponse.setDes("用户名不存在");
					}
			
				} else {
					loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
					loginResponse.setDes("请输入正确手机号！");
				}

			} else {
				loginResponse.setCode(BaseRes.ERRORPARAM_CODE);
				loginResponse.setDes("用户名密码不能为空");
			}
			logger.info("返回：" + mapper.writeValueAsString(loginResponse));
		} catch (Exception e) {
			e.printStackTrace();
			loginResponse.setCode(BaseRes.FAIL_CODE);
			loginResponse.setDes("系统繁忙请稍后再试！");
		}

		return loginResponse;
	}

	/**
	 * 注册新用户
	 * @param request
	 * @param loginRequest
	 * @return
	 */
	@RequestMapping(value = "/newRegist", method = RequestMethod.POST)
	@ResponseBody
	public Object regist(HttpServletRequest request,@RequestBody LoginRequest loginRequest) {
		RegistResponse registResponse = new RegistResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(loginRequest));
			String phoneNumber = loginRequest.getPhoneNumber();
			String code = loginRequest.getCode();
			String smsMessageSid = loginRequest.getSmsMessageSid();
			String regExp = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
			Pattern p = Pattern.compile(regExp);
			//邀请人
			String inviterUserUuid = loginRequest.getInviterUserUuid();
			/**
			 * 批次号
			 */
			Long batchId = loginRequest.getBatchId();
			boolean ifSmsRegist = StringUtils.isBlank(inviterUserUuid) ? false : true;
			boolean ifBatchId = (batchId == null || "".equals(batchId)) ? false : true;
			if(ifSmsRegist && ifBatchId){
				//被邀请注册时，不能绑定电子卡
				registResponse.setCode("3");
				registResponse.setDes("数据错误！被邀请注册时，不能绑定电子问答卡");
				return registResponse;
			}
			if(StringUtils.isNotBlank(loginRequest.getPwd()) && ifBatchId){
				//正常短信验证码及密码注册，不能绑定电子卡
				registResponse.setCode("3");
				registResponse.setDes("数据错误！正常短信验证码及密码注册，不能绑定电子问答卡");
				return registResponse;
			}
			if (phoneNumber != null && !phoneNumber.equals("") && (loginRequest.getPwd() != null || ifSmsRegist || ifBatchId) ) {
				Matcher m = p.matcher(phoneNumber);
				if (m.matches()) {
					User user = userService.getUserByphone(phoneNumber);
					if(code==null||code.equals("")){
						registResponse.setCode("3");//
						registResponse.setDes("验证码不能为空");
						return registResponse;
					}
					if(StringUtils.isBlank(smsMessageSid)){//判断短信验证码的Key是否存在
						registResponse.setCode("3");//
						registResponse.setDes("数据错误！");
						return registResponse;
					}
					if (user == null) {
						Map<String, String> checkSms = changeCodeService.checkSmsApp(smsMessageSid, code,phoneNumber);
						String codeValue = checkSms.get("code");
						if(codeValue.equals("1")){
							//正确
							//验证正确
							String userUuid = UUIDGenerator.getUUID();
							
							CookieUser cookieUser = new CookieUser();
							cookieUser.setPhoneNumber(userUuid);
							cookieUser.setPhone(phoneNumber);
							cookieUser.setDeviceType(loginRequest.getDeviceType());
							User registUser = new User();
							registUser.setRegisterDate(new Date());
							registUser.setPhoneNumber(userUuid);
							registUser.setPwd(loginRequest.getPwd());
							registUser.setPhone(phoneNumber);
							registUser.setRealName(phoneNumber.substring(0, 3).concat("****").concat(phoneNumber.substring(7)));
							//判断邀请人是否存在
							if(StringUtils.isNotBlank(inviterUserUuid)){
								User inviterUser = userService.getUserByPhoneNumber(inviterUserUuid);
								if(inviterUser != null){
									registUser.setInviteBy(inviterUserUuid);//邀请人
								}else{
									registResponse.setCode("3");//
									registResponse.setDes("此链接已失效！");
									return registResponse;
								}
							}
							//校验电子卡
							if(batchId != null && !"".equals(batchId)){
								//校验电子卡
								BaseRes<String> baseRes = cardBatchService.checkElectronicQACard(batchId);
								if(!"1".equals(baseRes.getCode())){
									registResponse.setCode("3");//
									registResponse.setDes(baseRes.getDes());
									return registResponse;
								}
							}
							userService.addUser(registUser);
							String cookie = CookieGenerator.generateCookie(userUuid);
							redisService.setObject(cookie, cookieUser, 0);
							registResponse.setCode("1");// 用户注册成功
							registResponse.setDes("恭喜你已注册成功！");
							registResponse.setCookieId(cookie);
							registResponse.setBalance(0.0);
							registResponse.setPhoneNumber(userUuid);
							registResponse.setPhone(phoneNumber);
							
							registResponse.setRole(1);
							IntegralService.integralRegist(userUuid);
							registResponse.setIntegralScore(1);
							
							/**
							 * 邀请注册双方得红包:主流程（金额为获取静态变量值）
							 * 1.被邀请人注册成功新增100元红包（已领状态）且用户问答卡余额增加
							 * 2.增加100元红包双向流水记录
							 * 3.邀请人新增15元红包（已领状态）且用户问答卡余额增加
							 * 4.增加15元红包双向流水记录
							 */
							//判断是否存在邀请人
							if(inviterUserUuid != null && !"".equals(inviterUserUuid)){
								//若存在
								//对当前注册用户增加100元问答红包
								RedEnvelopes redEnvelopes = new RedEnvelopes();
								redEnvelopes.setMoney(PayTypeUtil.REDENVELOPES_BEINVITATION_TO_REGISTER_QAMONEY);//金额
								redEnvelopes.setUserPhoneNum(userUuid);//领取红包的用户的用户主键
								redEnvelopes.setRedType(PayTypeUtil.REDENVELPES_BEINVITER);//红包类型
								//增加红包记录且用户问答卡余额增加
								redEnvelopesService.addQACardRedEnvelopes(redEnvelopes,null);
								registResponse.setAmount(PayTypeUtil.REDENVELOPES_BEINVITATION_TO_REGISTER_QAMONEY);
								
								//对邀请人用户增加15元问答红包
								redEnvelopes.setMoney(PayTypeUtil.REDENVELOPES_INVITATION_OTHER_QAMONEY);//金额
								redEnvelopes.setUserPhoneNum(inviterUserUuid);//领取红包的用户的用户主键-邀请人
								redEnvelopes.setRedType(PayTypeUtil.REDENVELPES_INVITER);//红包类型
								redEnvelopes.setQuestionUuid(userUuid);
								//增加红包记录且用户问答卡余额增加
								redEnvelopesService.addQACardRedEnvelopes(redEnvelopes,null);
							}else if(batchId != null && !"".equals(batchId)){
								//电子卡绑定
								BaseRes<String> baseRes = cardBatchService.bindingElectronicQACard(userUuid, batchId);
								registResponse.setAmount(baseRes.getAmount());
							}else{
								//个人注册得问答卡红包
								RedEnvelopes redEnvelopes = new RedEnvelopes();
								redEnvelopes.setMoney(PayTypeUtil.REDENVELOPES_REGISTER_QAMONEY);//金额
								redEnvelopes.setUserPhoneNum(userUuid);//领取红包的用户的用户主键
								redEnvelopes.setRedType(PayTypeUtil.REDENVELPES_REGISTER_QACARD);//红包类型
								//增加红包记录且用户问答卡余额增加
								redEnvelopesService.addQACardRedEnvelopes(redEnvelopes,null);
								registResponse.setAmount(PayTypeUtil.REDENVELOPES_REGISTER_QAMONEY);
								/**
								 * 如果不是邀请注册，则将绑定问答卡标志存到redis,共绑定问答卡时使用
								 */
								String redisKey = "regist" + cookie;
								redisService.set(redisKey, "1", 86400);
							}
						}else {
							//失败
							return checkSms;
						}
					} else {
						registResponse.setCode("3");//
						registResponse.setDes("用户已经存在，请直接登录");
					}
				} else {// 格式错误
					registResponse.setCode("3");//
					registResponse.setDes("请输入正确手机号");

				}
			} else {
				// 手机号或者密码不能为空
				registResponse.setCode("3");//
				registResponse.setDes("用户和密码不能为空");
			}
			logger.info("返回：" + mapper.writeValueAsString(registResponse));
		} catch (Exception e) {
			e.printStackTrace();
			registResponse.setCode("0");//
			registResponse.setDes("系统繁忙请稍后再试！");
		}
		return registResponse;
	}
	
    @RequestMapping("/imgCode")
    @ResponseBody
    public Object randCode( HttpServletResponse response) throws ServletException, IOException {
    	Map<String, String> map = new HashMap<String,String>();
		try {
			Map<String, String> imgCode = imgCode(response);
			
			String sRand = imgCode.get("code");
			String img = imgCode.get("img");
			Random random = new Random();
			String rands="";
			for (int i=0 ;i<4 ; i++) {
				String rand = String.valueOf(random.nextInt(10));
				rands+=rand;
			}
			long currentTimeMillis = System.currentTimeMillis();
			String randCode=rands+"_"+currentTimeMillis;
			redisService.set(randCode,sRand ,60);
			// 将生成的随机数字字符串写入Session
			map.put("img", img);
			map.put("randCode", randCode);
			map.put("code", "1");
		} catch (Exception e) {
			map.put("des", "网络抖动");
			map.put("code", "0");
		}
		
		return map;
		
        
    }
    
	 public Color getRandColor(int fc, int bc) {
	        Random rand = new Random();
	        if (fc > 255) {
	            fc = 255;
	        }
	        if (bc > 255) {
	            bc = 255;
	        }
	        int r = fc + rand.nextInt(bc - fc);
	        int g = fc + rand.nextInt(bc - fc);
	        int b = fc + rand.nextInt(bc - fc);
	        return new Color(r, g, b);
	    }
	 
	
	private Map<String, String> imgCode(HttpServletResponse response) throws IOException {
		Map<String, String> map = new HashMap<String,String>();
		// 首先设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 定义图片的宽度和高度
        int width = 90, height = 40;
        // 创建一个图像对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 得到图像的环境对象
        Graphics g = image.createGraphics();

        Random random = new Random();
        // 用随机颜色填充图像背景
        g.setColor(getRandColor(180, 250));
        g.fillRect(0, 0, width, height);
        for (int i = 0; i < 5; i++) {
            g.setColor(getRandColor(50, 100));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 4, 4);
        }
        // 设置字体，下面准备画随机数
        g.setFont(new Font("", Font.PLAIN, 40));
        // 随机数字符串
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            // 生成四个数字字符
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            // 生成随机颜色
            g.setColor(new Color(20 + random.nextInt(80), 20 + random.nextInt(100), 20 + random.nextInt(90)));
            // 将随机数字画在图像上
            g.drawString(rand, (17 + random.nextInt(3)) * i + 8, 34);

            // 生成干扰线
            for (int k = 0; k < 100; k++) {
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int xl = random.nextInt(9);
                int yl = random.nextInt(9);
                g.drawLine(x, y, x + xl, y + yl);
            }
        }
        //alogger.warn("生成的验证码为："+sRand);
        // 使图像生效
        g.dispose();
        // 输出图像到页面
        //ImageIO.write(image, "JPEG", response.getOutputStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        ImageIO.write(image, "JPEG", out);  
        String img = Base64.encodeBase64String(out.toByteArray());
        map.put("code", sRand);
        map.put("img", img);
		return map;
	}
	
	// 注册
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	@ResponseBody
	public Object newRegist(HttpServletRequest request,
			@RequestBody LoginRequest loginRequest) {
		RegistResponse registResponse = new RegistResponse();
		try {/*
			logger.info("接收：" + mapper.writeValueAsString(loginRequest));
			String phoneNumber = loginRequest.getPhoneNumber();
			String regExp = "^[1][3,4,5,7,8][0-9]{9}$";
			Pattern p = Pattern.compile(regExp);
			if (phoneNumber != null && !phoneNumber.equals("")
					&& loginRequest.getPwd() != null) {
				Matcher m = p.matcher(phoneNumber);
				if (m.matches()) {
					User user = userService.getUserByPhoneNumber(phoneNumber);
					if (user == null) {
						
							//正确
							//验证正确
						   String uuid = UUIDGenerator.getUUID();
							CookieUser cookieUser = new CookieUser();
							cookieUser.setPhoneNumber(uuid);
							cookieUser.setDeviceType(loginRequest.getDeviceType());
							User registUser = new User();
							registUser.setRegisterDate(new Date());
							registUser.setPhoneNumber(uuid);
							registUser.setPwd(loginRequest.getPwd());
							registUser.setPhone(phoneNumber);
							userService.addUser(registUser);
							String cookie = CookieGenerator
									.generateCookie(uuid);
							redisService.setObject(cookie, cookieUser, 0);
							registResponse.setCode("1");// 用户注册成功
							registResponse.setDes("恭喜你已注册成功！");
							registResponse.setCookieId(cookie);
							registResponse.setBalance(0.0);
							registResponse.setPhoneNumber(uuid);
							registResponse.setPhone(phoneNumber);
							registResponse.setRole(1);
					} else {
						registResponse.setCode("3");//
						registResponse.setDes("用户已经存在，请直接登录");
					}
				} else {// 格式错误
					registResponse.setCode("3");//
					registResponse.setDes("请输入正确手机号");

				}
			} else {

				// 手机号或者密码不能为空
				registResponse.setCode("3");//
				registResponse.setDes("用户和密码不能为空");
			}
			logger.info("返回：" + mapper.writeValueAsString(registResponse));
		*/
			registResponse.setCode("3");//
			registResponse.setDes("请更新版本");
		} catch (Exception e) {
			e.printStackTrace();
			registResponse.setCode("0");//
			registResponse.setDes("系统繁忙请稍后再试！");
		}

		return registResponse;
	}

	// 找回密码第一步  版本跟新 v2.0.4
	@RequestMapping(value = "/newFindPwdOne", method = RequestMethod.POST)
	@ResponseBody
	public Object newFindPwnOne(HttpServletRequest request,
			@RequestBody FindPwdOneRequest findPwdRequest) {
		FindPwdOneResponse findPwdOneResponse = new FindPwdOneResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(findPwdRequest));
			String phoneNumber = findPwdRequest.getPhoneNumber();
			String code = findPwdRequest.getCode();
			String pwd = findPwdRequest.getPwd();
			String conPwd = findPwdRequest.getConPwd();
			String smsMessageSid = findPwdRequest.getSmsMessageSid();
			
			if (StringUtils.isBlank(phoneNumber)||!StringUtils.isMobile(phoneNumber)) {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
				findPwdOneResponse.setDes("请输入正确手机号！");
				return findPwdOneResponse;
				
			}
			if (StringUtils.isBlank(code)) {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
				findPwdOneResponse.setDes("请输入短信验证码！");
				return findPwdOneResponse;
			}
			
			if (StringUtils.isBlank(pwd)) {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
				findPwdOneResponse.setDes("请输入密码！"+ResponseCode.RESPOSNE_CODE_1007);
				return findPwdOneResponse;
			}
			
			if (StringUtils.isBlank(conPwd)) {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
				findPwdOneResponse.setDes("请输入确认密码！"+ResponseCode.RESPOSNE_CODE_1007);
				return findPwdOneResponse;
			}
			if (StringUtils.isBlank(smsMessageSid)) {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
				findPwdOneResponse.setDes(BaseRes.ERRORPARAM_DES+ResponseCode.RESPOSNE_CODE_1006);
				return findPwdOneResponse;
			}
			if (!pwd.equals(conPwd)) {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
				findPwdOneResponse.setDes("两次输入密码不一致！"+ResponseCode.RESPOSNE_CODE_1006);
				return findPwdOneResponse;
			}
			
			
			
			User user = userService.getUserByphone(phoneNumber);
			if (user != null) {
				String userId = user.getPhoneNumber();
				Map<String, String> checkSms = changeCodeService.checkSmsApp(smsMessageSid, code,phoneNumber);
				
				if (checkSms==null) {
					findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);//
					findPwdOneResponse.setDes("验证码失效！");
					return findPwdOneResponse;
				}else {
					String string = checkSms.get("code");
					if (!string.equals(BaseRes.SUCCESS_CODE)) {
						return checkSms;
					}
					User record = new User();
					
					record.setPhoneNumber(userId);
					record.setPwd(pwd);
					userService.updateUser(record);
					String cookie = CookieGenerator.generateCookie(phoneNumber);
					Set<String> keys = redisService.keys("C_" + phoneNumber
							+ "*");

					for (String key : keys) {
						redisService.delete(key);
					}
					
					CookieUser cookieUser = new CookieUser();
					cookieUser.setPhoneNumber(userId);
					cookieUser.setPhone(user.getPhone());
					redisService.setObject(cookie, cookieUser, 0);
					LoginResponse userInformation = userService.userInformation(userId);
					
					userInformation.setCookieId(cookie);
					userInformation.setCode(BaseRes.SUCCESS_CODE);
					userInformation.setDes("找回密码成功");
					return userInformation;
					
					
				}

			} else {
				findPwdOneResponse.setCode(BaseRes.ERRORPARAM_CODE);
				findPwdOneResponse.setDes("账号未注册请先进行注册！");
			}
				
			
		
			logger.info("返回：" + mapper.writeValueAsString(findPwdOneResponse));
		} catch (Exception e) {

			e.printStackTrace();
			findPwdOneResponse.setCode("0");
			findPwdOneResponse.setDes("系统繁忙请稍后再试！");
		}

		return findPwdOneResponse;

	}
	// 找回密码第一步
	@RequestMapping(value = "/findPwdOne", method = RequestMethod.POST)
	@ResponseBody
	public Object findPwnOne(HttpServletRequest request,
			@RequestBody FindPwdOneRequest findPwdRequest) {
		FindPwdOneResponse findPwdOneResponse = new FindPwdOneResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(findPwdRequest));
			String phoneNumber = findPwdRequest.getPhoneNumber();
			if (phoneNumber!= null
					&&!phoneNumber.equals("")) {
				
				boolean mobile = StringUtils.isMobile(phoneNumber);
				if(mobile){
					//User user = userService.getUserByPhoneNumber(phoneNumber);// 根据号码查到的用户信息
					User user = userService.getUserByphone(phoneNumber);
					
					if (user != null) {
						findPwdOneResponse.setCode("1");
					} else {
						findPwdOneResponse.setCode("3");
						findPwdOneResponse.setDes("账号未注册请先进行注册！");
					}
				
				}else {
					findPwdOneResponse.setCode("3");
					findPwdOneResponse.setDes("请输入正确的手机号");
				}
		} else {
				findPwdOneResponse.setCode("3");
				findPwdOneResponse.setDes("手机号不能为空！");
			}
			logger.info("返回：" + mapper.writeValueAsString(findPwdOneResponse));
		} catch (Exception e) {

			e.printStackTrace();
			findPwdOneResponse.setCode("0");
			findPwdOneResponse.setDes("系统繁忙请稍后再试！");
		}

		return findPwdOneResponse;

	}

	// 找回密码第二步
	@RequestMapping(value = "/findPwdTwo", method = RequestMethod.POST)
	@ResponseBody
	public Object findPwd(HttpServletRequest request,
			@RequestBody LoginRequest findPwdRequest) {
		LoginResponse findPwdResponse = new LoginResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(findPwdRequest));
			String phoneNumber = findPwdRequest.getPhoneNumber();
			String pwd = findPwdRequest.getPwd();
			if (phoneNumber != null && !phoneNumber.equals("") && pwd != null) {
				//User user = userService.getUserByPhoneNumber(phoneNumber);// 根据号码查到的用户信息
				User user = userService.getUserByphone(phoneNumber);
				
				if (user != null) {
					User record = new User();
					String phoneNumber2 = user.getPhoneNumber();
					
					record.setPhoneNumber(phoneNumber2);
					record.setPwd(pwd);
					userService.updateUser(record);
					String cookie = CookieGenerator.generateCookie(phoneNumber2);
					Set<String> keys = redisService.keys("C_" + phoneNumber2
							+ "*");

					for (String key : keys) {
						redisService.delete(key);
					}
					
					CookieUser cookieUser = new CookieUser();
					cookieUser.setPhoneNumber(phoneNumber2);
					cookieUser.setPhone(phoneNumber);
					redisService.setObject(cookie, cookieUser, 0);
					LoginResponse userInformation = userService.userInformation(phoneNumber2);
					
					userInformation.setCookieId(cookie);
					userInformation.setCode("1");
					userInformation.setDes("找回密码成功");
					return userInformation;
				} else {
					findPwdResponse.setCode("3");
					findPwdResponse.setDes("账号未注册请您先进行注册");
				}
			} else {
				findPwdResponse.setCode("3");
				findPwdResponse.setDes("账号或者密码不能为空");
			}
			logger.info("返回：" + mapper.writeValueAsString(findPwdResponse));
		} catch (Exception e) {
			e.printStackTrace();
			findPwdResponse.setCode("0");
			findPwdResponse.setDes("系统繁忙请稍后再试！");

		}

		return findPwdResponse;

	}

	// 退出登录
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@ResponseBody
	public Object logoutUser(HttpServletRequest request) {
		AddAdmireResponse logoutResponse = new AddAdmireResponse();
		try {
			logger.info("接收："
					+ mapper.writeValueAsString(request.getHeader("cookieId")));

			String cookieId = request.getHeader("cookieId");
			if(cookieId!=null&&!cookieId.equals("")){
				redisService.delete(cookieId);
				logoutResponse.setCode("1");
			}else {
				//
				logoutResponse.setCode("3");
				logoutResponse.setDes("数据格式错误");
			}
			logger.info("返回：" + mapper.writeValueAsString(logoutResponse));
		} catch (Exception e) {
			e.printStackTrace();
			logoutResponse.setCode("0");
			logoutResponse.setDes("系统繁忙");
		}
		return logoutResponse;
	}
	
	//获取验证码
	
	@RequestMapping(value = "/change", method = RequestMethod.POST)
	@ResponseBody
	public Object changCode(HttpServletRequest request,
			@RequestBody FindPwdOneRequest findPwdRequest) {
		FindPwdOneResponse findPwdOneResponse = new FindPwdOneResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(findPwdRequest));
			String phoneNumber = findPwdRequest.getPhoneNumber();
			if (phoneNumber!= null
					&& !phoneNumber.equals("")) {
				boolean mobile = StringUtils.isMobile(phoneNumber);
				if(mobile){
					User user = userService.getUserByPhoneNumber(findPwdRequest
							.getPhoneNumber());// 根据号码查到的用户信息

					if (user == null) {
						StringBuilder str=new StringBuilder();//定义变长字符串
						Random random=new Random();
						//随机生成数字，并添加到字符串
						for(int i=0;i<4;i++){
						    str.append(random.nextInt(10));
						}
						String code=str.toString();
						//调短信接口
						String[] string={code,"5"};
						String sendSms = smsSendService.sendSms("8aaf070858bd37890158ccd0b71b04f0", "143866", phoneNumber, string);
						if(sendSms!=null){
							//成功以后
							redisService.set(phoneNumber+"_code", code, 300);
							findPwdOneResponse.setCode("1");
						}else {
							//
							findPwdOneResponse.setCode("3");
							findPwdOneResponse.setDes("获取验证码失败 ，请重新获取");
						}
						

					} else {
						findPwdOneResponse.setCode("3");
						findPwdOneResponse.setDes("已注册！");
					}
				
				}else {
					findPwdOneResponse.setCode("3");
					findPwdOneResponse.setDes("请输入正确的手机号");
				}
			} else {
				findPwdOneResponse.setCode("3");
				findPwdOneResponse.setDes("手机号不能为空！");
			}
			logger.info("返回：" + mapper.writeValueAsString(findPwdOneResponse));
		} catch (Exception e) {

			e.printStackTrace();
			findPwdOneResponse.setCode("0");
			findPwdOneResponse.setDes("系统繁忙请稍后再试！");
		}

		return findPwdOneResponse;

	}

	// 注册
		@RequestMapping(value = "/h5regist", method = RequestMethod.POST)
		@ResponseBody
		public Object h5Regist(HttpServletRequest request,
				@RequestBody LoginRequest loginRequest) {
			RegistResponse registResponse = new RegistResponse();
			try {
				logger.info("接收：" + mapper.writeValueAsString(loginRequest));
				String phoneNumber = loginRequest.getPhoneNumber();
				String code = loginRequest.getCode();
				String smsMessageSid = loginRequest.getSmsMessageSid();
				
				String regExp = "^[1][3,4,5,7,8][0-9]{9}$";
				Pattern p = Pattern.compile(regExp);
				if (phoneNumber != null && !phoneNumber.equals("")
						&& loginRequest.getPwd() != null) {
					Matcher m = p.matcher(phoneNumber);
					if (m.matches()) {
						//User user = userService.getUserByPhoneNumber(phoneNumber);
						User user = userService.getUserByphone(phoneNumber);
						if (user == null) {
							Map<String, String> checkSms = changeCodeService.checkSms(smsMessageSid, code);
							String codeValue = checkSms.get("code");
							if(codeValue.equals(Global.SUCCESS)){
								//正确
								//验证正确
								String uuid = UUIDGenerator.getUUID();
								CookieUser cookieUser = new CookieUser();
								cookieUser.setPhoneNumber(uuid);
								cookieUser.setPhone(phoneNumber);
								User registUser = new User();
								registUser.setRegisterDate(new Date());
								registUser.setPhoneNumber(uuid);
								registUser.setPhone(phoneNumber);
								registUser.setPwd(loginRequest.getPwd());
								userService.addUser(registUser);
								String cookie = CookieGenerator
										.generateCookie(uuid);
								redisService.setObject(cookie, cookieUser, 0);
								registResponse.setCode("1");// 用户注册成功
								registResponse.setDes("恭喜你已注册成功！");
								registResponse.setCookieId(cookie);
								registResponse.setBalance(0.0);
								registResponse.setPhoneNumber(uuid);
								registResponse.setPhone(phoneNumber);
								registResponse.setRole(1);
							}else {
								//失败
								return checkSms;
							}
						
							
					} else {
							registResponse.setCode("3");
							registResponse.setDes("用户已经存在，请直接登录");
						}
					} else {// 格式错误
						registResponse.setCode("3");
						registResponse.setDes("请输入正确手机号");

					}
				} else {

					// 手机号或者密码不能为空
					registResponse.setCode("3");
					registResponse.setDes("用户和密码不能为空");
				}
				logger.info("返回：" + mapper.writeValueAsString(registResponse));
			} catch (Exception e) {
				e.printStackTrace();
				registResponse.setCode("0");//
				registResponse.setDes("系统繁忙请稍后再试！");
			}

			return registResponse;
		}
		
		
		// 找回密码第一步
	@RequestMapping(value = "/h5findPwdOne", method = RequestMethod.POST)
	@ResponseBody
	public Object h5FindPwnOne(HttpServletRequest request,
			@RequestBody FindPwdOneRequest findPwdRequest) {
		FindPwdOneResponse findPwdOneResponse = new FindPwdOneResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(findPwdRequest));
			String phoneNumber = findPwdRequest.getPhoneNumber();
			String code = findPwdRequest.getCode();
			String smsMessageSid = findPwdRequest.getSmsMessageSid();
			
			if (phoneNumber!= null
					&&!phoneNumber.equals("")) {
				boolean mobile = StringUtils.isMobile(phoneNumber);
				if(mobile){
					//User user = userService.getUserByPhoneNumber(phoneNumber);// 根据号码查到的用户信息
					User user =userService.getUserByphone(phoneNumber);
					if (user != null) {
						Map<String, String> checkSms = changeCodeService.checkSms(smsMessageSid, code);
						String codeValue = checkSms.get("code");
						if(codeValue.equals(Global.SUCCESS)){
							findPwdOneResponse.setCode("1");
						}else {
							return checkSms;
						}
					} else {
						findPwdOneResponse.setCode("3");
						findPwdOneResponse.setDes("账号未注册请先进行注册！");
					}
				
				}else {
					findPwdOneResponse.setCode("3");
					findPwdOneResponse.setDes("请输入正确的手机号");
				}
		} else {
				findPwdOneResponse.setCode("3");
				findPwdOneResponse.setDes("手机号不能为空！");
			}
			logger.info("返回：" + mapper.writeValueAsString(findPwdOneResponse));
		} catch (Exception e) {

			e.printStackTrace();
			findPwdOneResponse.setCode("0");
			findPwdOneResponse.setDes("系统繁忙请稍后再试！");
		}

		return findPwdOneResponse;

	}
	
		
	
	
	 //修改密码
	  
	@RequestMapping(value = "/upatePwd", method = RequestMethod.POST)
	@ResponseBody
	public Object upatePwd(HttpServletRequest request,
	@RequestBody UpdatePwdRequest updatePwdRequest) {
		HashMap<String,String> map = new HashMap<String, String>();
		try {
			String cookieId = request.getHeader("cookieId");
			if(cookieId!=null){
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				if(cookieUser!=null){
					String phoneNumber = cookieUser.getPhoneNumber();
					//String userId = cookieUser.getUserId();
					
					User user = userService.getUserByPhoneNumber(phoneNumber);
					//User user =userService.getUserByphone(phoneNumber);
					if(user!=null){
						String phoneNumber2 = user.getPhoneNumber();
						String oldPwd = updatePwdRequest.getOldPwd();
						String newPwd = updatePwdRequest.getNewPwd();
						if((StringUtils.isNotBlank(oldPwd) || "0".equals(updatePwdRequest.getUpdateType())) && (StringUtils.isNotBlank(newPwd))){
							String pwd = user.getPwd();
							if("0".equals(updatePwdRequest.getUpdateType()) || oldPwd.equals(pwd)){
								User user2 = new User();
								user2.setPhoneNumber(phoneNumber2);
								user2.setPwd(newPwd);
								userService.updateUser(user2);
								map.put("code", "1");
								map.put("des", "修改成功");
							}else {
								//原密码错误
								map.put("code", "3");
								map.put("des", "原密码错误");
							}
						}else {
							map.put("code", "3");
							map.put("des", "原密码和新密码不能为空");
						}
						
						
					}else {
						map.put("code", "2");
						map.put("des", "重新登录");
					}
				}else {
					map.put("code", "2");
					map.put("des", "重新登录");
				}

			}else {
				map.put("code", "2");
				map.put("des", "重新登录");
			}
		} catch (Exception e) {
			map.put("code", "0");
			map.put("des", "网路繁忙！");
		}
	
		return map;
	}
	/**
	 * 绑定问答卡
	 * @param request
	 * @param baseRes
	 * @return
	 */
	@RequestMapping(value = "/bindingQACard", method = RequestMethod.POST)
	@ResponseBody
	public Object bindingQACard(HttpServletRequest request,@RequestBody Card card) {
		BaseRes<?> baseRes = new BaseRes();
		//获取用户信息
		String cookieId = request.getHeader("cookieId");
		//cookieId不存在时，重新登录
		if(cookieId == null || "".equals(cookieId)){
			baseRes.setCode("2");
			baseRes.setDes("重新登录");
			return baseRes;
		}
		//获取用户信息
		CookieUser cookieUser = redisService.getObejct(cookieId,CookieUser.class);
		//获取用户主键
		String phoneNumber = cookieUser.getPhoneNumber();
		//用户主键不存在时，重新登录
		if(phoneNumber == null || "".equals(phoneNumber)){
			baseRes.setCode("2");
			baseRes.setDes("重新登录");
			return baseRes;
		}
		User user =userService.getUserByPhoneNumber(phoneNumber);
		//判断用户是否已经绑定渠道或者问答卡
		Long userSrc = user.getUserSrc();
		if(userSrc != null && !"".equals(userSrc)){
			baseRes.setCode("0");
			baseRes.setDes("已绑定渠道");
			return baseRes;
		}
		//获取Redis，判读是否允许绑定问答卡
		String redisKey = "regist" + cookieId;
		String bindingString = redisService.get(redisKey);
		if(bindingString != null && !"".equals(bindingString)){
			//激活问答卡
			baseRes = cardService.bindingQACard(cookieId, phoneNumber, card);
			if("1".equals(baseRes.getCode())){
				redisService.delete(redisKey);	
			}
		}else{
			baseRes.setCode("3");
			baseRes.setDes("已超时");
			return baseRes;
		}
		return baseRes;
	}
	
	/**
	 * 邀请记录
	 * @param request
	 * @param baseRes
	 * @return
	 */
	@RequestMapping(value = "/inviterUserRecord", method = RequestMethod.POST)
	@ResponseBody
	public Object inviterUserRecord(HttpServletRequest request,@RequestBody PageRequest pageRequest) {
		SearchResponse searchResponse = new SearchResponse();
		//获取用户信息
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		//获取用户主键
		String phoneNumber = cookieUser.getPhoneNumber();
		//用户主键不存在时，重新登录
		if(phoneNumber == null || "".equals(phoneNumber)){
			searchResponse.setCode("2");
			searchResponse.setDes("重新登录");
			return searchResponse;
		}
		//查询邀请红包记录
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("userPhoneNum", phoneNumber);//用户主键
		params.put("redType", PayTypeUtil.REDENVELPES_INVITER);//红包类型
		
		//数据起始索引
		int sinceId = pageRequest.getSinceId();
		//数据结束索引
		int maxId = pageRequest.getMaxId();
		
		//数据索引-逻辑处理
		if (sinceId <= 0) {
			sinceId = 1;
		}
		if (maxId <= 0 || maxId < sinceId) {
			maxId = sinceId;
		}
		params.put("pageIndex", sinceId - 1);
		params.put("pageSize", maxId - sinceId + 1);
		searchResponse.setCode("1");
		searchResponse.setDatas(redEnvelopesService.selectRedEnvelopesByParams(params));
		searchResponse.setAmount(redEnvelopesService.countRedEnvelopesByParams(params));
		if(searchResponse.getDatas() == null || searchResponse.getDatas().size() < 0){
			searchResponse.setDes("无记录");
		}
		searchResponse.setRows(searchResponse.getDatas().size());
		return searchResponse;
	}
	/**
	 * 查看（分享的）文章/围观详情接口
	 * @param request
	 * @param paramsMap
	 * @return
	 */
	@RequestMapping(value = "/openShareDetails/share", method = RequestMethod.POST)
	@ResponseBody
	public Object openShareDetails(HttpServletRequest request,@RequestBody Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Object shareTypeObject = paramsMap.get("shareType");
		Object uuidObject = paramsMap.get("uuid");
		String shareType = null;
		String uuid = null;
		if(shareTypeObject == null || "".equals(shareTypeObject)
				|| uuidObject == null || "".equals(uuidObject)){
			resultMap.put("code", "3");
			resultMap.put("des", "数据错误！");
			return resultMap;
		}else{
			shareType = shareTypeObject.toString();
			uuid = uuidObject.toString();
		}
		if(PayTypeUtil.REDENVELPES_SHARE_ARTICLE.equals(shareType)){
			Article article = articelService.getArticleById(uuid);
			//根据主键获取文章
			if (article == null || "".equals(article)) {
				resultMap.put("code", "3");
				resultMap.put("des", "文章不存在！");
				return resultMap;
			}
			//标题
			resultMap.put("title", article.getTitle());
			//内容
			resultMap.put("content", article.getDescription());
			//时间
			resultMap.put("createDate", article.getCreateDate());
			
			//用户信息
			UserLevel userLevel = article.getUserLevel();
			String counselorDutyName = counselorDutyService.getCounselorDutyName(userLevel.getCounselorDuty());
			userLevel.setCounselorDuty(counselorDutyName);
			resultMap.put("realName", userLevel.getRealName());//昵称
			resultMap.put("headImage", userLevel.getHeadImage());//头像
			resultMap.put("levelName", userLevel.getLevelName());//级别名称
			resultMap.put("counselorDuty", userLevel.getCounselorDuty());//职责名称
			
			String articleCategoryId = article.getCategory().getUuid();
			CmsCategory cmsCategorys = cmsArticleService.getCmsCategoryById(articleCategoryId);
			resultMap.put("categoryName", cmsCategorys.getName());//文章标签
		}else if(PayTypeUtil.REDENVELPES_SHARE_SECRETLY.equals(shareType)){
			QuestionExample questionExample = new QuestionExample();
			questionExample.setPageIndex(0);
			questionExample.setPageSize(1);
			Criteria criteria = questionExample.createCriteria();
			criteria.andStatusEqualTo(3);
			criteria.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
			criteria.andDelFlagEqualTo(Global.SHOW);
			criteria.andUuidEqualTo(uuid);
			List<QuestionEx> onlookQuestion = questionExService.getOnlookQuestion(questionExample);
			if(onlookQuestion != null && onlookQuestion.size() == 1){
				QuestionEx questionEx = onlookQuestion.get(0);
				resultMap.put("realName", questionEx.getRealName());//用户名
				resultMap.put("content", questionEx.getContent());//问题内容
				resultMap.put("lookNum", questionEx.getLookNum());//围观数
				resultMap.put("approveNum", questionEx.getApproveNum());//点赞数
				resultMap.put("area", questionEx.getArea());//省份
				resultMap.put("trade", questionEx.getQuTrade());//行业
				resultMap.put("date", questionEx.getDate());//日期
				resultMap.put("headImage", questionEx.getHeadImage());
			}else{
				resultMap.put("code", "3");
				resultMap.put("des", "围观不存在！");
				return resultMap;
			}
		}else{
			resultMap.put("code", "3");
			resultMap.put("des", "数据错误！");
			return resultMap;
		}
		resultMap.put("code", "1");
		return resultMap;
	}
	
	/**
	 * 小红点显示
	 * @param request
	 * @param paramsMap
	 * @return
	 */
	@RequestMapping(value = "redPoint", method = RequestMethod.POST)
	@ResponseBody
	public Object redPoint(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//获取用户信息
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		//获取用户主键
		String phoneNumber = cookieUser.getPhoneNumber();
		//用户主键不存在时，重新登录
		if(phoneNumber == null || "".equals(phoneNumber)){
			resultMap.put("code", "2");
			resultMap.put("des", "重新登录");
			return resultMap;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", phoneNumber);
		resultMap = messageService.countForRedPoint(map);
		resultMap.put("code", "1");
		return resultMap;
	}
}
